﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Eco.ObjectRepresentation;
using Eco.ViewModel.Runtime;
using EcoProject1;
using EcoProject1.ViewModelCodeGen_UploadAttachment;

namespace MvcApplication1.Controllers
{
    public class AttachmentsController : ModelDrivenController
    {
        //
        // GET: /Attachments/

      public ActionResult Navigate(string id, string view)
      {
        var obj=this.ObjectForId(id).GetValue<Ticket>();

        return View(view, UploadAttachment.Create(this.EcoSpace, obj));
      }


      [AcceptVerbs(HttpVerbs.Post)]
      public ActionResult Upload(VMClass model, HttpPostedFileBase TheFile)
        {
          if (TheFile != null)
          {
            Ticket ticket = this.EcoSpace.ExternalIds.ObjectForId(model.ThisAsExternalId).GetValue<Ticket>();
            var ta=new TicketAttachment(EcoSpace);
            ta.Name=Path.GetFileName(TheFile.FileName);
            using (BinaryReader br = new BinaryReader(TheFile.InputStream))
            {
              ta.Data = br.ReadBytes((int)TheFile.InputStream.Length);
            }
            ticket.TicketAttachments.Add(ta);
            Commit();
            return RedirectToAction("Display", "ModelDriven", new { id = model.ThisAsExternalId, view = "Ticket" });
          }
          return RedirectToAction("Navigate", new { id = model.ThisAsExternalId, view = "UploadAttachment" });
        }
    }
}
